package com.example.fasttask;

import java.text.DateFormat;
import java.text.ParseException;
import java.util.Date;
import java.util.List;

import android.app.ListActivity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckedTextView;
import android.widget.ListAdapter;
import android.widget.ListView;

public class EditListActivity extends ListActivity {
	private TaskTranslator translator;
	private int ctr = 0;
	private Button deleteButton;
	private int checkBoxesChecked;
	private ArrayAdapter<Task> adapter;
	private BroadcastReceiver receiver;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_edit_list);
		deleteButton = (Button)findViewById(R.id.delete);
		checkBoxesChecked = 0;

		translator = new TaskTranslator(this);
		translator.open();


		List<Task> values = translator.getAllTasks();

		adapter = new ArrayAdapter<Task>(this, android.R.layout.simple_list_item_checked, values);
		setListAdapter(adapter);

		ListView lv = getListView();
		lv.setTextFilterEnabled(true);
		lv.setOnItemClickListener(new CheckListener());
		lv.setAdapter(adapter);

		registerForContextMenu(lv);
		boolean add = true;
		try {
			Log.d("q", "item 0$$: " + adapter.getItem(0).isDefault());
		}
		catch (Exception e) {}
		for(int i = 0; i < adapter.getCount(); i++) {
			Log.d("q", "item " + i + ": " + adapter.getItem(i).isDefault());
			if(adapter.getItem(i).isDefault()) {
				add = false;
				break;
			}
		}
		if(add)
			addDefaultTasks();

		IntentFilter filter = new IntentFilter("my.action");
		receiver = new BroadcastReceiver() {
			public void onReceive(Context context, Intent intent) {
				translator.open();
				
				Log.d("q", "broadcast received. action: " + intent.getAction());
				if(intent.getAction().equals("my.action")) {
						String name =  intent.getStringExtra("name");
						Log.d("q", "name: " + name);
						int len = Integer.parseInt(intent.getStringExtra("length"));
						Log.d("q", "len: " + len);
						DateFormat df = DateFormat.getDateInstance();
						Date date = new Date();
						try {
							date = df.parse( intent.getStringExtra("date"));
						} catch (ParseException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
							Log.d("q", "error parsing date");
						}
						Log.d("q", "date: " + date.toString());
						String recur = intent.getStringExtra("recur");
						boolean isRecur = false;
						if(recur.equals("true")) isRecur = true;
						Log.d("q", "isRecur: " + isRecur);

						translator.open();
						Task q =  translator.createTask(name, len, date, isRecur);
						Log.d("q", "task created");
						
						adapter.add(q);
//						addChild();
						
						for(int i = 0; i < adapter.getCount(); i++)
							Log.d("q", "AD - item" + i + ": " + adapter.getItem(i));	
						List<Task> values = translator.getAllTasks();
						int x = 0;
						for(Task t: values) {
							Log.d("q", "DB - item " + x + ": " + t);
							x++;
						}
						translator.close();
						adapter.notifyDataSetChanged();
				}
			}
		};

		adapter.notifyDataSetChanged();
		registerReceiver(receiver, filter);

	}

//	public void addChild() {
//		CheckedTextView ctv = new CheckedTextView(this);
//		getListView().addView(ctv);
//	}
	
	private class CheckListener implements AdapterView.OnItemClickListener {
		public void onItemClick(AdapterView<?> av, View v, int position, long id) {
			CheckedTextView check = (CheckedTextView)v;
			if (!check.isChecked()) {
				deleteButton.setVisibility(0);	//show delete button
				checkBoxesChecked++;
			}
			else {
				checkBoxesChecked--;
				if (checkBoxesChecked == 0) {
					deleteButton.setVisibility(8);	//hide delete button
				}
			}
			check.setChecked(!check.isChecked());
			Task t = adapter.getItem(position);
			t.setChecked(!t.isChecked());
		}
	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		super.onCreateContextMenu(menu, v, menuInfo);
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.context_menu, menu);
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
		switch (item.getItemId()) {
		case R.id.context_menu:

			return true;
		default:
			return super.onContextItemSelected(item);
		}
	}

    private void addDefaultTasks() {
    	adapter.add((translator.createTask("Take a power nap", 30, new Date(), true)).setDefault(true));
    	adapter.add((translator.createTask("Take a power nap", 20, new Date(), true)).setDefault(true));
    	adapter.add((translator.createTask("Deep breathing", 5, new Date(), true)).setDefault(true));
    	adapter.add((translator.createTask("Jumping Jacks!", 1, new Date(), true)).setDefault(true));
    	adapter.add((translator.createTask("Learn how to count to five in a new language", 5, new Date(),
    			true)).setDefault(true));
    	adapter.add((translator.createTask("Do your laundry", 10, new Date(), true)).setDefault(true));
    	adapter.add((translator.createTask("Do 20 push-ups", 1, new Date(), true)).setDefault(true));
    	adapter.add((translator.createTask("Think about your dream vacation", 10, new Date(), true)).setDefault(true));
    	Log.d("q", "item??: " + adapter.getItem(0).isDefault());
    }
	public void onClick(View view) {
		@SuppressWarnings("unchecked")
		Task t;
		switch (view.getId()) {
		case R.id.add:
			//			t = translator.createTask("dummy task" + ctr++, 5, new Date(), true);
			//			adapter.add(t);
			Intent intent = new Intent(EditListActivity.this, EditTaskActivity.class);
			startActivity(intent);
			break;
		case R.id.delete:
			view.setVisibility(8);
			int size = adapter.getCount();
			if (size > 0) {
				int x = 0;
				while(x < adapter.getCount()) {
					Log.d("q", "size: " + adapter.getCount());
					Log.d("q", "x: " + x);
					t = adapter.getItem(x);
					Log.d("q", "isChecked?: " + t.isChecked());
					if(t.isChecked()) {
						translator.deleteTask(t);
						adapter.remove(t);
					}
					else x++;
				}
			}
			clearAllChecks();
			break;
		}
		adapter.notifyDataSetChanged();
	}
	
	public void clearAllChecks() {
		ListView lv = getListView();
		for(int i = 0; i < lv.getCount(); i++) {
			((CheckedTextView)lv.getChildAt(i)).setChecked(false);
		}
	}
	
	public void startMainActivity(View view) {
		Intent intent = new Intent(EditListActivity.this, MainActivity.class);
        startActivity(intent);
        finish();
	}

	@Override
	protected void onResume() {
		translator.open();
		super.onResume();
	}

	@Override
	protected void onPause() {
		translator.close();
		super.onPause();
	}
	
	@Override
	protected void onDestroy() {
		unregisterReceiver(receiver);
		super.onDestroy();
	}
}
